import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { KiRequestConfig, KiRequestInterceptors } from './type'
import { ElLoading } from 'element-plus'
import 'element-plus/theme-chalk/el-loading.css'
const DEFAULT_SHOW = true
class KiRequest {
  instance: AxiosInstance
  interceptors?: KiRequestInterceptors
  isShowLoading:boolean
  loading?:any
  constructor(config:KiRequestConfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.isShowLoading = config.isShowLoading || DEFAULT_SHOW

    this.instance.interceptors.request.use(
      this.interceptors?.requestSuccessInterceptor,
      this.interceptors?.requestErrorInterceptor
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseSuccessInterceptor,
      this.interceptors?.responseErrorInterceptor
    )

    this.instance.interceptors.request.use(config => {
      if (this.isShowLoading) {
        this.loading = ElLoading.service({
          lock: true,
          text: '正在请求数据....',
          background: 'rgba(0, 0, 0, 0.5)'
        })
      }
      return config
    }, err => {
      return err
    })

    this.instance.interceptors.response.use(res => {
      this.loading?.close()
      return res
    }, err => {
      this.loading?.close()
      return err
    })
  }

  request(config: AxiosRequestConfig):Promise<AxiosResponse> {
    return new Promise((resolve, reject) => {
      if (this.interceptors?.requestSuccessInterceptor) {
        config = this.interceptors.requestSuccessInterceptor(config)
      }
      this.instance.request(config).then(res => {
        resolve(res)
      }, err => {
        reject(err)
      })
    })
  }
  get(config: AxiosRequestConfig) {
    return this.request({
      ...config,
      method:'GET'
    })
  }
  post(config: AxiosRequestConfig) {
    return this.request({
      ...config,
      method:'POST'
    })
  }
  delete(config: AxiosRequestConfig) {
    return this.request({
      ...config,
      method:'DELETE'
    })
  }
  patch(config: AxiosRequestConfig) {
    return this.request({
      ...config,
      method:"PATCH"
    })
  }
}

export default KiRequest